package com.ruoyi.project.notice.type.controller;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.notice.type.domain.NoticeType;
import com.ruoyi.project.notice.type.service.NoticeTypeService;
import com.ruoyi.project.system.post.domain.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/notice/type")
public class NoticeTypeController  extends BaseController {

    @Autowired
    private NoticeTypeService  noticeTypeService;


    //访问templates 文件的前缀
    String  prefix="notice/type";

    @GetMapping("")
    public String operlog()
    {
        return prefix + "/show";
    }

    //模糊查询
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NoticeType noticeType)
    {
        //开启分页
        startPage();
        List<NoticeType> list = noticeTypeService.findMore(noticeType);

        return getDataTable(list);
    }
    /**
     * 新增公告
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated NoticeType noticeType)
    {
        if (UserConstants.TYPE__NAME_NOT_UNIQUE.equals(noticeTypeService.checkTypeNameUnique(noticeType)))
        {
            return error("新增通知类型'" + noticeType.getTname() + "'失败，原因<类型名称已存在>");
        }
                            //返回int rows受影响行数
        return toAjax(noticeTypeService.insertType(noticeType));
    }


    /**
     * 修改公告
     */
    @GetMapping("/edit/{tid}")
    //ModelMap对象主要用于传递控制方法处理数据到结果页面
    public String edit(@PathVariable("tid") Long tid, ModelMap mmap)
    {
        mmap.put("type", noticeTypeService.selectTypeById(tid));
        return prefix + "/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    //@Validated  : 数据格式校验
    public AjaxResult editSave(@Validated NoticeType noticeType)
    {
        return toAjax(noticeTypeService.updateType(noticeType));
    }


    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        System.out.println("要删除的公告id:"+ids);
        try
        {
            return toAjax(noticeTypeService.deleteTypeByIds(ids));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 校验公告名称
     */
    @PostMapping("/checkTypeNameUnique")
    @ResponseBody
    public String checkTypeNameUnique(NoticeType  noticeType)
    {
        return noticeTypeService.checkTypeNameUnique(noticeType);
    }


}
